﻿namespace ScrumFactory.Data.Sql
{
    using System.Collections.Generic;
    using System.ComponentModel.Composition;
    using System.Linq;

    [Export(typeof(IProjectsRepository))]
    public class SqlProjectsRepository : IProjectsRepository
    {
        private string connectionString;

        [ImportingConstructor()]
        public SqlProjectsRepository(
            [Import("ScrumFactoryEntitiesConnectionString")]
            string connectionString)
        {
            this.connectionString = connectionString;
        }

        public ICollection<ScrumFactory.Project> GetAllProjects()
        {
            using (var context = new ScrumFactoryEntities(this.connectionString))
            {
                // EntityFramework does not recognize the extension method directly
                // that is why we call .ToList() to retrieve the whole resultset
                // and then we translate each entitiy
                return context.Projects.ToList().Select(p => p.ToModel()).ToList();
            }
        }

        public ScrumFactory.Project GetProject(string id)
        {
            using (var context = new ScrumFactoryEntities(this.connectionString))
            {
                // EntityFramework does not recognize the extension method directly
                // that is why we call .ToList() to retrieve the whole resultset
                // and then we translate the entitiy
                return context.Projects.Where(p => p.Id == id).ToList().Select(p => p.ToModel()).SingleOrDefault();
            }
        }

        public void InsertProject(ScrumFactory.Project project)
        {
            using (var context = new ScrumFactoryEntities(this.connectionString))
            {
                context.AddObject("Projects", project.ToDataModel());
                context.SaveChanges();
            }
        }

        public void UpdateProject(ScrumFactory.Project project)
        {
            using (var context = new ScrumFactoryEntities(this.connectionString))
            {
                var projectEntity = context.Projects.First(p => p.Id == project.Id);
                projectEntity.Name = project.Name;

                context.SaveChanges();
            }
        }
    }
}
